package com.iphanta.community.following.service.impl;

import com.baidu.fsg.uid.UidGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iphanta.community.common.UserUtils;
import com.iphanta.community.common.message.CommunityMessage;
import com.iphanta.community.common.message.MessageContent;
import com.iphanta.community.common.utils.JsonUtils;
import com.iphanta.community.following.entity.Dynamic;
import com.iphanta.community.following.entity.HandPicked;
import com.iphanta.community.following.mapper.DynamicMapper;
import com.iphanta.community.following.mapper.HandPickedMapper;
import com.iphanta.community.following.service.DynamicService;
import com.iphanta.community.following.service.HandPickedService;
import com.iphanta.community.following.traffic.*;
import com.iphanta.community.following.traffic.vo.Droplet;
import com.iphanta.community.mq.message.ChatMessage;
import com.iphanta.community.tags.service.TagsService;
import com.iphanta.community.user.entity.UserBasicInfo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 墨声 E-mail: zehong.hongframe.huang@gmail.com
 * create time: 3/11/22 2:27 PM
 */
@Service
public class HandPickedServiceImpl implements HandPickedService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HandPickedServiceImpl.class);

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private HandPickedMapper handPickedMapper;

    @Autowired
    private DynamicMapper dynamicMapper;

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public HandPickedResponse selected(HandPickedRequest request) {
        HandPicked handPicked = new HandPicked();
        handPicked.setId(this.uidGenerator.getUID());
        handPicked.setDynamicId(request.getDynamicId());
        handPicked.setCreateTime(new Date());
        this.handPickedMapper.insert(handPicked);
        HandPickedResponse response = new HandPickedResponse();
        response.setDynamicId(handPicked.getDynamicId());
        return response;
    }

    @Override
    public HandPickedListResponse list(HandPickedListRequest request) {
        HandPickedListResponse response = new HandPickedListResponse();
        List<HandPicked> handPick = this.handPickedMapper.selectRecently(request.getCursor());
        if (handPick.size() < 11) {
            //TODO 先去查MySQL
            response.setCursor(-1L);
        } else {
            response.setCursor(handPick.get(10).getDynamicId());
            handPick.remove(10);
        }
        if (CollectionUtils.isEmpty(handPick)) {
            response.setFlow(Collections.EMPTY_LIST);
            return response;
        }
        List<Long> dynamicIds = handPick.stream().map(e -> e.getDynamicId()).collect(Collectors.toList());
        List<Dynamic> dynamics = this.dynamicMapper.selectByIds(UserUtils.getUid(), dynamicIds);

        response.setFlow(this.dynamicService.dynamic2Flow(dynamics));
        return response;
    }

    @Value("${hand-picked.tag_codes}")
    private String codes;

    @Autowired
    private TagsService tagsService;

    @Override
    public HandPickedTagsResponse tags() {
        HandPickedTagsResponse response = new HandPickedTagsResponse();
        response.setTags(this.tagsService.tags(codes));
        return response;
    }

    @XxlJob("handpicked")
    @Transactional(rollbackFor = Exception.class)
    public ReturnT<String> handpicked(String param) {
       try {
           List<Dynamic> dynamics = this.dynamicMapper.likeCountgreaterThan20();
           if(CollectionUtils.isEmpty(dynamics)) {
               return ReturnT.SUCCESS;
           }
           dynamics.forEach(c -> {
               c.setTagCodes(c.getTagCodes() + "|1000001");
               c.setIsHandPicked(1);
               c.setUpdateTime(new Date());
           });
           this.dynamicMapper.batchUpdateDynamic(dynamics);
           List<HandPicked> handPickeds = dynamics.stream().map(e -> {
               HandPicked handPicked = new HandPicked();
               handPicked.setId(this.uidGenerator.getUID());
               handPicked.setDynamicId(e.getId());
               handPicked.setCreateTime(e.getCreateTime());
               return handPicked;
           }).collect(Collectors.toList());
           this.handPickedMapper.batchInsert(handPickeds);
           dynamics.forEach(dynamic -> {
               ChatMessage chat = new ChatMessage();
               chat.setFrom(1);
               chat.setTo(dynamic.getUid());
               CommunityMessage message = new CommunityMessage();
               message.setType(3);
               MessageContent content = new MessageContent();
               content.setText(dynamic.getContext());
               String intro = JsonUtils.INSTANCE.toJson(dynamic.getResJson()).get(0).asText();
               content.setUrl(intro);
               content.setDynamicId(dynamic.getId().toString());
               message.setContent(content);
               chat.setCommunityMessage(message);
               this.rocketMQTemplate.syncSend("sys-chat-notifications", new GenericMessage(chat));
           });
           return ReturnT.SUCCESS;
       } catch (Exception e) {
           LOGGER.error("", e);
           return ReturnT.FAIL;
       }
    }
}
